﻿using SQLite;
using System.Linq.Expressions;
using MG.Library.Models;

namespace MG.Library.Services;

public class MgStorage : IMGStorage
{
    public const string DbName = "maogaiDB.sqlite3";

    public static readonly string MgDbPath =
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);

    private SQLiteAsyncConnection _connection;

    private SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(MgDbPath);

    private readonly IPreferenceStorage _preferenceStorage;

    public MgStorage(IPreferenceStorage preferenceStorage)
    {
        _preferenceStorage = preferenceStorage;
    }

    public bool IsInitialized =>
        _preferenceStorage
            .Get(MgStorageConstant.DbVersionKey, 0) == 
        MgStorageConstant.Version;

    public async Task InitializeAsync()
    {
        await using var dbFileStream =
            new FileStream(MgDbPath, FileMode.OpenOrCreate);
        await using var dbAssetStream =
            typeof(MgStorage).Assembly.GetManifestResourceStream(DbName);
        await dbAssetStream.CopyToAsync(dbFileStream);

        _preferenceStorage.Set(MgStorageConstant.DbVersionKey,
            MgStorageConstant.Version);
    }

    public Task<Mg> GetMgAsync(int id) =>
        Connection.Table<Mg>().FirstOrDefaultAsync(p => p.Id == id);

    public async Task<IEnumerable<Mg>> GetMgsAsync(
        Expression<Func<Mg, bool>> where, int skip, int take) =>
        await Connection.Table<Mg>().Where(where).Skip(skip).Take(take)
            .ToListAsync();

    public async Task CloseAsync() => await Connection.CloseAsync();
}
 
public static class MgStorageConstant
{
    public const String DbVersionKey=
        nameof (MgStorageConstant) + "."+nameof (DbVersionKey);

    public const int Version = 1; 
}